<template>
  <el-dialog
    :title="dialist.isAdd ? '添加商品分类' : '编辑商品分类'"
    :visible.sync="dialist.isShow"
    center
    :before-close="cancle"
  >
    <el-form :model="list" ref="diaform" :rules="rules">
      <el-form-item label="上级分类" :label-width="formLabelWidth" prop="pid">
        <el-select v-model="list.pid" placeholder="请选择上级分类">
          <el-option label="顶级分类" :value="0"></el-option>
          <el-option
            v-for="item in menuOption"
            :key="item.id"
            :label="item.catename"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="分类名称"
        :label-width="formLabelWidth"
        prop="catename"
      >
        <el-input
          v-model="list.catename"
          autocomplete="off"
          placeholder="请输入分类名称"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="图片"
        :label-width="formLabelWidth"
        v-show="list.pid != 0"
      >
        <!-- 
          on-preview 这个是文件上传后点击触发的函数
          on-remove 这个是文件上传后点击删除 触发的函数
          action 图片上传地址，#没有上传地址
          list-type  picture-card缩略图
          auto-upload 会根据action里面的地址。自动上传
          on-change文件改变时的钩子函数，上传成功和失败都会调用
         -->
        <el-upload
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :on-change="filechange"
          :file-list="fileList"
          :on-remove="remove"
          :on-preview="preview"
          :limit="1"
           :on-exceed="handleExceed"
        >
          <i class="el-icon-zoom-in"></i>
        </el-upload>
        <!-- 放大功能 -->
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="状态" :label-width="formLabelWidth">
        <el-switch
          v-model="list.status"
          :active-value="1"
          :inactive-value="2"
        ></el-switch>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancle">取 消</el-button>
      <el-button type="primary" v-if="dialist.isAdd" @click="add"
        >添 加</el-button
      >
      <el-button type="primary" v-else @click="edit">编 辑</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addCate, getCaterOne, editCate, getCatelist } from "../../util/axios";
import {mapActions} from "vuex"
export default {
  data() {
    return {
      list: {
        pid: 0,
        catename: "",
        img: "",
        status: 2,
      },
      fileList: [],
      formLabelWidth: "120px",
      rules: {
        catename: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        pid: [{ required: true, message: "请选择菜单", trigger: "blur" }],
      },
      menuOption: [],
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  props: ["dialist"],
  methods: {
    //超出上传限制后的处理
     handleExceed(files,fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
    //点击取消后隐藏dialog
    cancle() {
      //隐藏dialog
      this.$emit("cancle", false);
      //清空表格
      this.list = {
        pid: 0,
        catename: "",
        img: "",
        status: 1,
      };
      //清空验证
      this.$refs.diaform.resetFields();
      //清空回显图片的验证
      this.fileList=[];
      //清空功能验证
      this.dialogVisible = false;
      this.dialogImageUrl ="";
    },
    //出现图片放大预览功能
    preview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //点击图片删除的功能
    remove() {    
      this.fileList = [];
      this.list.img = "";
      this.dialogVisible = false;
      this.dialogImageUrl ="";
    },
    ...mapActions({
        getCatelist:"mSort/getSortList"
    }),
    //添加功能
    add() {
      this.$refs.diaform.validate((val) => {
        if (val) {
          //文件添加使用的是FormData，需要提交新的表单数据 给表单数据要用append,一项一项添加
          //所以需要使用对象循环
          console.log(data);
          let data = new FormData();
          for (let i in this.list) {
            data.append(i, this.list[i]);
          }
          addCate(data)
            .then((res) => {
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.getCatelist();
                this.cancle()
                data = null;
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch((err) => {
              this.$message.error(err.msg);
            });
        }
      });
    },
    //dialog的编辑
    edit() {
      this.$refs.diaform.validate((val) => {
        if (val) {
       
          console.log(data);
          let data = new FormData();
          for (let i in this.list) {
            data.append(i, this.list[i]);
          }
          editCate(data)
            .then((res) => {
              if (res.code == 200) {
                this.$message.success(res.msg);
                 this.getCatelist();
                this.cancle()
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch((err) => {
              this.$message.error(err.msg);
            });
        }
      });
    },
    lookup(id) {
      getCaterOne({ id }).then((res) => {
        if (res.code == 200) {
            
            this.list = res.list;
            this.list.id = id;
            //绑定属性可以回显 图片
            this.fileList = this.list.img ? [{ url:this.list.img }]:[];
            
     
        }
      });
    },
    //
    filechange(file) {
      this.list.img = file.raw;
      // console.log(this.list.img);
    },
  },
  mounted() {
    //页面挂载后循环数据
      getCatelist({ pid: 0 }).then((res) => {
      if (res.code == 200) {
        this.menuOption = res.list;
      } else {
        this.$message.error(res.msg);
      }
    });
  },
};
</script>

<style lang="stylus" scoped></style>